package org.thirdHero.wx.response;

import com.github.binarywang.wxpay.bean.result.WxPayBaseResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.impl.WxPayServiceAbstractImpl;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import org.apache.commons.lang3.StringUtils;
import org.thirdHero.wx.utils.WxSignUtils;

import java.util.Map;

public class WxProfitBaseResult extends WxPayBaseResult {

    @XStreamOmitField
    private String signType;

    public void checkResult(WxPayServiceAbstractImpl wxPayService) throws WxPayException {
        //校验返回结果签名
        Map<String, String> map = toMap();
        if (getSign() != null && !WxSignUtils.checkSign(map, wxPayService.getConfig().getMchKey(),signType)) {
            this.getLogger().debug("校验结果签名失败，参数：{}", map);
            throw new WxPayException("参数格式校验错误！");
        }

        //校验结果是否成功
        if (!StringUtils.equalsAny(StringUtils.trimToEmpty(getReturnCode()).toUpperCase(), "SUCCESS", "")
                || !StringUtils.equalsAny(StringUtils.trimToEmpty(getResultCode()).toUpperCase(), "SUCCESS", "")) {
            StringBuilder errorMsg = new StringBuilder();
            if (getReturnCode() != null) {
                errorMsg.append("返回代码：").append(getReturnCode());
            }
            if (getReturnMsg() != null) {
                errorMsg.append("，返回信息：").append(getReturnMsg());
            }
            if (getResultCode() != null) {
                errorMsg.append("，结果代码：").append(getResultCode());
            }
            if (getErrCode() != null) {
                errorMsg.append("，错误代码：").append(getErrCode());
            }
            if (getErrCodeDes() != null) {
                errorMsg.append("，错误详情：").append(getErrCodeDes());
            }

            this.getLogger().error("\n结果业务代码异常，返回結果：{},\n{}", map, errorMsg.toString());
            throw WxPayException.from(this);
        }
    }
    public String getSignType() {
        return signType;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }
}
